package com.cy.java.basic;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Reflect {


    public static void main(String[] args) throws Exception {
        method();
        Class c1 = Student.class;
        //method2(c1);//获取反射方法们
        //method3(c1);//获取反射成员变量们
        //method4(c1);//反射构造方法们
        //method5(c1);//利用反射创建对象
        //method6(c1);//利用发射给成员变量set/get
        //method7(c1);//利用反射运行方法
    }

    private static void method7(Class c1) throws Exception {
        //getMethod(方法名,参数类型的class对象)
        Method m = c1.getMethod("show",int.class);
        Object oo = c1.newInstance();
        //invoke(1,2)  1是对象,2是方法具体要传入的参数
        m.invoke(00,10000);
    }

    private static void method6(Class c1) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Field f = c1.getField("age");
        //set(1,2)   1是对象,2给属性赋的具体值
        Object o = c1.newInstance();
        f.set(o,1000);
    }

    private static void method5(Class x) throws Exception {
        //利用反射 触发 无参构造 创建对象
        Object s = x.newInstance();
        System.out.println(s);
        //利用反射触发含参构造创建对象
        //getConstructor的参数 是String类型的Class对象
        Constructor c = x.getConstructor(String.class);
        //newInstance的参数 是给构造方法传入的具体的参数
        Object o = c.newInstance("jack");
        System.out.println(o);
    }

    private static void method4(Class x) {
        Constructor[] cs = x.getConstructors();
        for (Constructor c : cs){
            System.out.println(c.getName());
            Class[] cs2 = c.getParameterTypes();
            System.out.println(Arrays.toString(cs2));
        }
    }

    private static void method3(Class x) {
        Field[] fs = x.getFields();
        for (Field f : fs){
            System.out.println(f.getName());
            System.out.println(f.getType().getName());
        }
    }

    private static void method2(Class x) {
        Method[] ms = x.getMethods();
        for (Method m : ms){
          String name = m.getName();
            System.out.println(name);
            //获取参数类型
            Class[] cs = m.getParameterTypes();
            System.out.println(Arrays.toString(cs));
        }
    }

    //三种方式
    //1.Class.forName("类名")
    //2.类名.class
    //3.对象.getClass()
    private static void method() throws ClassNotFoundException {
        //三种方式获取Class对象
        Class c1 = String.class;
        Class c2 = new String().getClass();
        Class c3 = Class.forName("java.lang.String");
        //一个JVM只有一个字节码对象
        System.out.println(c1==c2);//true
        System.out.println(c2==c3);//true
    }
}
